package com.example.verificationcode;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/admin")
public class VerificationCodeController {
    private static final String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";
    private static final String KAPTCHA_SESSION_DATE = "KAPTCHA_SESSION_DATE";
    private static final long TIME_OUT = 60 * 1000;

    @RequestMapping("/check")
    public boolean check(String inputVerificationCode, HttpSession session) {
//        1.判断输入的验证码是否为空
        if (!StringUtils.hasLength(inputVerificationCode)) {
            return false;
        }

//        2.获取后台生成的验证码的有关信息
        String saveVerificationCode = (String)session.getAttribute(KAPTCHA_SESSION_KEY);
        Date saveVerificationCodeDate = (Date)session.getAttribute(KAPTCHA_SESSION_DATE);

//        3.对比用户输入的验证码和后台生成的验证码是否一致
        if(inputVerificationCode.equalsIgnoreCase(saveVerificationCode)) { //不区分大小写
//            4. 确认验证码是否过期
            if (saveVerificationCodeDate != null && System.currentTimeMillis() - saveVerificationCodeDate.getTime() < TIME_OUT) {
                return true;
            }
        }
        return false;
    }
}
